package mahjong.auto.com.automahjong;

import android.content.Context;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;

/**
 * 浮动窗口
 * 需要权限　<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
 * Created by heqian on 17-8-14.
 */

public class FloatActivity extends LinearLayout implements View.OnTouchListener {
    protected final WindowManager mManage;
    //   protected final View mView;
    protected final WindowManager.LayoutParams mParams;
    private int lastX, lastY;
    private int paramX, paramY;
    private boolean isMoveWindow = true;

    public FloatActivity(Context context, int id) {
        super(context);

        mManage = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        mParams = new WindowManager.LayoutParams();
        mParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        mParams.format = PixelFormat.RGBA_8888; // 设置图片格式，效果为背景透明
        mParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        mParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        mParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        mParams.gravity = Gravity.TOP | Gravity.LEFT;

        LayoutInflater.from(context).inflate(id, this);

        setGravity(Gravity.TOP | Gravity.LEFT);
        mManage.addView(this, mParams);
        this.setOnTouchListener(this);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastX = (int) event.getRawX();
                lastY = (int) event.getRawY();
                paramX = mParams.x;
                paramY = mParams.y;
                break;
            case MotionEvent.ACTION_MOVE:
                int dx = (int) event.getRawX() - lastX;
                int dy = (int) event.getRawY() - lastY;
                mParams.x = paramX + dx;
                mParams.y = paramY + dy;
                mManage.updateViewLayout(this, mParams);
                break;
        }
        return true;
    }

    public boolean isMoveWindow() {
        return isMoveWindow;
    }

    public void setMoveWindow(boolean moveWindow) {
        if (moveWindow)
            this.setOnTouchListener(this);
        else
            this.setOnTouchListener(null);

        isMoveWindow = moveWindow;
    }
}
